package com.example.mdm4

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

class FlowActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_flow)
//        lifecycleScope.launch {
//            fun1()
//        }

        fun2()
    }

    suspend fun fun1(){
//        withTimeoutOrNull(3000){
            flow<Int> {
                for (i in 0..10){
                    delay(500)
                    println("emit:$i")
                    emit(i)
                }
            }.buffer(3,BufferOverflow.SUSPEND)
                .collect{
                    delay(2000)
                println(it)
            }
//        }
    }

    fun fun2()= runBlocking{
        val list = flowOf(1, 2, 4, 5, 6, 7, 9)
            .filter {
                it % 3 == 0
            }
            /*.map {
                it*2
            }*/
            .onEach {
                println("${Thread.currentThread().name}: $it")
//                delay(500)
            }.flowOn(Dispatchers.Default)
            .toList()
        println(list.toString())
            /*.collect{
                println("collect:${Thread.currentThread().name}: $it")
                println(it)
        }*/
    }
}